package com.changeover.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.changeover.domain.IEntity;

public abstract class AbstractDao<T extends IEntity> implements IDao<T>{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public List<T> getAll() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from " + getEntityClass().getName());
		@SuppressWarnings("unchecked")
		List<T> list = query.list();
		return list;
	}
	
	public T get(Serializable id) {
		Session session = sessionFactory.getCurrentSession();
		@SuppressWarnings("unchecked")
		T entity = (T)session.get(getEntityClass(), id);
		return entity;
	}
	
	public void delete(T entity) {
		Session session = getSessionFactory().getCurrentSession();
		session.delete(entity);
	}
	
	public void delete(Serializable id) {
		Session session = getSessionFactory().getCurrentSession();
		session.delete(get(id));
	}
	
	public void saveOrUpdate(T entity) {
		Session session = getSessionFactory().getCurrentSession();
		session.saveOrUpdate(entity);
	}
	
	protected SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	abstract protected Class<T> getEntityClass();

}
